package net.wendal.nutzbook.module;

import javax.servlet.http.HttpSession;

import net.wendal.nutzbook.bean.User;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

//配置Ioc相关注解及属性,即IocBean,Inject和Dao属性

@IocBean
@At("/user")//入口函数对应的 URL
@Ok("json")//成功视图
@Fail("http:500")//失败视图
public class UserModule {

    @Inject //注入
    protected Dao dao;
    
    @At //入口函数对应的 URL
    public int count() {
        return dao.count(User.class);
    }

    @At //入口函数对应的 URL
    public Object login(@Param("username")String name, @Param("password")String password, HttpSession session) {
        User user = dao.fetch(User.class, Cnd.where("name", "=", name).and("password", "=", password));
        if (user == null) {
            return false;
        } else {
            session.setAttribute("me", user.getId());
            return true;
        }
    }
    
    @At
    @Ok(">>:/")
    public void logout(HttpSession session) {
        session.invalidate();
    }
}
